package com.andy.module.widget

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ConvertUtils

/**
 * @creator:LuoFan
 * @date:2022/6/7
 * @description:
 */
class MenuGridDecoration : RecyclerView.ItemDecoration() {

    var verticalSpace = 0
    var horizontalSpace = 0
    var columnCount = 3
    private var index = 0

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildLayoutPosition(view)
        if (position == 0) {
            index = 0
        }
        val layoutManager = parent.layoutManager
        if (layoutManager is GridLayoutManager) {
            when (layoutManager.spanSizeLookup.getSpanSize(position)) {
                1 -> {
                    //左侧为(当前条目数-1)/总条目数*divider宽度
                    outRect.left = index * horizontalSpace / columnCount
                    //右侧为(总条目数-当前条目数)/总条目数*divider宽度
                    outRect.right = (columnCount - index - 1) * horizontalSpace / columnCount
                    outRect.bottom = verticalSpace
                    index++
                }
                columnCount -> {
                    index = 0
                    outRect.bottom = verticalSpace
                    if (position != 0) {
                        outRect.top = ConvertUtils.dp2px(8f)
                    }
                }
            }
        }
    }
}